package MessageOp;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import java.net.DatagramPacket;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import Logcheck.CheckConstant;
import serve.Constant;
import UserFriend.FriendConstant;

public class GetMessage
{

    public static JSONObject getMessage(DatagramPacket datagramPacket)
    {
        JSONObject jsonObject = JSONObject.parseObject(new String(datagramPacket.getData()));
        String username = jsonObject.getString("username");

        JSONObject send_json = new JSONObject();
        int code = CheckConstant.False;
        String message = "";
        JSONArray data = new JSONArray();

        try
        {
            boolean is_message_get = false;
            String sql = "select * from %s where receiver=\"%s\"";
            sql = String.format(sql,FriendConstant.message_table,username);
            Statement stmt = Constant.chatdbConnector.getChatdb_connection().createStatement();
            ResultSet res = stmt.executeQuery(sql);

            is_message_get = res.next();
            if(!is_message_get)
            {
                code = CheckConstant.False;
                message = MessageConstant.message_get_failed;
            }
            else
            {
                code = CheckConstant.True;
                message = MessageConstant.message_get_succeed;
                while (is_message_get)
                {
                    String s = res.getString(2);
                    //System.out.print(s);
                    data.add(JSONObject.parseObject(s));
                    is_message_get = res.next();
                }
            }

            //System.out.print("准备删除");
            DeleteMessage.deleteMessage(username);

        }catch (SQLException e)
        {
            e.printStackTrace();
        }

        send_json.put("code",code);
        send_json.put("message",message);
        send_json.put("data",data);

        return send_json;
    }
}
